package tech.xs.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.xs.common.framework.domain.entity.TreeEntity;
import tech.xs.common.framework.service.CrudServiceImpl;
import tech.xs.sys.dao.SysWebMenuDao;
import tech.xs.sys.domain.bo.web.menu.ImportExportWebMenuBo;
import tech.xs.sys.domain.entity.SysWebMenu;
import tech.xs.sys.service.SysWebMenuService;

import java.util.List;

@Service
public class SysWebMenuServiceImpl extends CrudServiceImpl<SysWebMenuDao, SysWebMenu> implements SysWebMenuService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importWebMenu(List<ImportExportWebMenuBo> importMenus) {
        for (ImportExportWebMenuBo importMenu : importMenus) {
            boolean isExist = count(Wrappers.<SysWebMenu>lambdaQuery().eq(TreeEntity::getCode, importMenu.getCode())) > 0;
            if (isExist) {
                update(Wrappers.<SysWebMenu>lambdaUpdate()
                        .set(StrUtil.isNotBlank(importMenu.getFatherCode()), TreeEntity::getFatherCode, importMenu.getFatherCode())
                        .set(StrUtil.isBlank(importMenu.getFatherCode()), TreeEntity::getFatherCode, null)
                        .set(SysWebMenu::getName, importMenu.getName())
                        .set(SysWebMenu::getShowName, importMenu.getShowName())
                        .set(importMenu.getOrderValue() != null, SysWebMenu::getOrderValue, importMenu.getOrderValue())
                        .set(StrUtil.isNotBlank(importMenu.getPageUri()), SysWebMenu::getPageUri, importMenu.getPageUri())
                        .set(StrUtil.isBlank(importMenu.getPageUri()), SysWebMenu::getPageUri, null)
                        .set(importMenu.getMenuStatus() != null, SysWebMenu::getMenuStatus, importMenu.getMenuStatus())
                        .set(StrUtil.isNotBlank(importMenu.getRemark()), SysWebMenu::getRemark, importMenu.getRemark())
                        .set(StrUtil.isBlank(importMenu.getRemark()), SysWebMenu::getRemark, null)
                        .eq(TreeEntity::getCode, importMenu.getCode())
                );
            } else {
                SysWebMenu saveData = new SysWebMenu();
                saveData.setCode(importMenu.getCode());
                saveData.setFatherCode(importMenu.getFatherCode());
                saveData.setName(importMenu.getName());
                saveData.setShowName(importMenu.getShowName());
                saveData.setOrderValue(importMenu.getOrderValue());
                saveData.setPageUri(importMenu.getPageUri());
                saveData.setMenuStatus(importMenu.getMenuStatus());
                saveData.setRemark(importMenu.getRemark());
                save(saveData);
            }
        }
    }
}
